﻿using AutoMapper;
using B.MES.Customer.Application.Application;
using B.MES.Customer.Application.IApplication;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Linq.Expressions;
using Yitter.IdGenerator;

namespace B.MES.Customer.Read.WebApi.Controllers
{
    /// <summary>
    /// RBAC管理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RBACController : ControllerBase
    {
        /// <summary>
        /// 注入RBAC应用层服务
        /// </summary>
        private readonly IRBACApplication _rbacApplication;
        /// <summary>
        /// AutoMapper服务
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// NLog日志
        /// </summary>
        private readonly ILogger<RBACController> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="rbacApplication">RBAC应用层服务</param>
        public RBACController(IRBACApplication rbacApplication, IMapper mapper, ILogger<RBACController> logger)
        {
            _rbacApplication = rbacApplication;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginInput">包含用户名和密码的登录信息</param>
        /// <returns>根据用户名查询到的用户信息</returns>
        [HttpPost]
        public IActionResult UserLogin(InputLogin loginInput)
        {
         
                _logger.LogInformation("执行登录方法");
                if (loginInput == null)
                {
                    return BadRequest("输入错误");
                }

                var login = _mapper.Map<InputLogin>(loginInput);
                var logininfo = _rbacApplication.UserLogin(login);
                if (logininfo == null)
                {
                    return BadRequest("账号或者密码错误");
                }
                return Ok(logininfo);
         
           
        }


        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="Password">需要加密的密码</param>
        /// <returns>加密之后的密码</returns>
        [HttpGet]
        public IActionResult GetMD5Pwd(string Password)
        {
            return Ok(_rbacApplication.GetMD5Pwd(Password));
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns>返回包含验证码的ActionResult</returns>
        [HttpGet]
        public IActionResult GetVerification()
        {
            //生成随机数
            Random rand = new Random();
            //生成4位验证码
            var result = GenerateVerificationCode(rand, 4);
            //返回包含有验证码的APIresult
            return Ok(new { result });
        }

        /// <summary>
        /// 生成验证码的方法
        /// </summary>
        /// <param name="rand">用于生成随机数的Random实例</param>
        /// <param name="length">验证码的长度</param>
        /// <returns>返回生成的验证码</returns>
        private string GenerateVerificationCode(Random rand, int length)
        {
            // 字符集，包含数字和大小写字母
            const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            char[] codeArray = new char[length];

            // 从字符集中随机选择字符来构建验证码
            for (int i = 0; i < length; i++)
            {
                codeArray[i] = chars[rand.Next(chars.Length)];
            }
            //返回生成的验证码
            return new string(codeArray);
        }


        /// <summary>
        /// 用户查询+分页+显示
        /// </summary>
        /// <param name="user_Name"></param>
        /// <param name="u_Name"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserListByKeyword(string? user_Name, string? u_Name, int page, int size)
        {
            return Ok(_rbacApplication.GetUserListByKeyword(user_Name, u_Name, page, size));
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="requestUserDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddUser(RequestUserDTO requestUserDTO)
        {
            var result = _rbacApplication.AddUser(requestUserDTO);
            return Ok(result);
        }

        /// <summary>
        /// 单个删除（真删除）
        /// </summary>
        /// <param name="user_Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult UserDeleteData(string user_Id)
        {
            try
            {
                return Ok(_rbacApplication.UserDeleteData(user_Id));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult BatchDeleteData(List<User> list)
        {
            return Ok(_rbacApplication.BatchDeleteData(list));
        }

        /// <summary>
        /// 显示菜单
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMemus(string userId)
        {
            PageApiResut<MemuDTO> pageApiResut = new PageApiResut<MemuDTO>();
            pageApiResut.Data = _rbacApplication.GetMemus(userId);
            return Ok(pageApiResut);
        }

        /// <summary>
        /// 显示全部菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMemusAll()
        {
            PageApiResut<MemuDTO> pageApiResut = new PageApiResut<MemuDTO>();
            pageApiResut.Data = _rbacApplication.GetMemus();
            return Ok(pageApiResut);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="requestUserDTO"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdateUser(RequestUserDTO requestUserDTO)
        {
            try
            {
                return Ok(_rbacApplication.UpdateUser(requestUserDTO));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 用户反填
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserSel(string userId)
        {
            try
            {
                return Ok(_rbacApplication.GetUserSel(userId));
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
